package com.example.demoinfluxdb;

/**
 * <b><code>QueryBuilder 自定义查询</code></b>
 * <b>Create Time:</b> 2025/11/279:25
 * <p>description: </p>
 *
 * @author qd.yt  --... ..... ..--- --... .---- -..-. -.-. --- --
 * @version 0.0.1
 * @since demo-influxdb v0.0.1
 */
import java.util.ArrayList;
import java.util.List;

public class QueryBuilder {
    private List<Condition> conditions;

    public QueryBuilder() {
        this.conditions = new ArrayList<>();
    }

    public void addCondition(String field, String comparison, Object value, String logic) {
        this.conditions.add(new Condition(field, comparison, value, logic));
    }

    public String buildQuery(String tableName) {
        if (conditions.isEmpty()) {
            return "SELECT * FROM " + tableName + ";";
        }

        StringBuilder query = new StringBuilder("SELECT * FROM " + tableName + " WHERE ");

        for (int i = 0; i < conditions.size(); i++) {
            Condition condition = conditions.get(i);
            query.append(condition.field).append(" ").append(condition.comparison).append(" ");

            if (condition.value instanceof String) {
                query.append("'").append(condition.value).append("'");
            } else {
                query.append(condition.value);
            }

            if (i < conditions.size() - 1) {
                query.append(" ").append(condition.logic.toUpperCase()).append(" ");
            }
        }

        query.append(";");
        return query.toString();
    }

    private static class Condition {
        String field;
        String comparison;
        Object value;
        String logic;

        public Condition(String field, String comparison, Object value, String logic) {
            this.field = field;
            this.comparison = comparison;
            this.value = value;
            this.logic = logic;
        }
    }

    public static void main(String[] args) {
        QueryBuilder queryBuilder = new QueryBuilder();
        queryBuilder.addCondition("error_count", "=", 40, "AND"); // 整数条件
        queryBuilder.addCondition("battery_level", ">=", 33.50, "AND"); // 浮点数条件
        queryBuilder.addCondition("humidity", ">=", 50.3, "OR"); // 字符串条件
        queryBuilder.addCondition("temperature", "<", -0.1, "OR"); // 字符串条件

        String sqlQuery = queryBuilder.buildQuery("sensor_data");
        System.out.println(sqlQuery);
    }
}
